package com.example.levine.taobaolivecheck;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Path;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;

import com.example.levine.taobaolivecheck.tools.L;
import com.example.levine.taobaolivecheck.tools.ScreenUtils;
import com.example.levine.taobaolivecheck.tools.TShow;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Admin on 2016/11/17.
 */

public class MyService extends AccessibilityService {
    /**
     * 匹配条件
     */
    //直播中匹配条件
    public static final String LIVING_1 = "亲密度";
    public static final String LIVING_2 = "跟主播聊什么?";
    public static final String LIVING_ID_1 = "com.taobao.taobao:id/taolive_room_num_layout";
    public static final String LIVING_ID_2 = "com.taobao.taobao:id/taolive_favor_icon_config";
    public static final String LIVING_ID_3 = "com.taobao.taobao:id/taolive_gift_list_btn";
    public static final String LIVING_ID_CLOSE = "com.taobao.taobao:id/taolive_close_btn";

    //已停播匹配条件
    public static final String LIVED_1 = "精彩回放";
    public static final String LIVED_2 = "主播个人页";
    public static final String LIVED_3 = "完整版";
    public static final String LIVED_4 = "粉丝群";


    public static final String MONITOR_PACKAGE_NAMES = "com.taobao.taobao";

    public static final String LIVED = "LIVED";
    public static final String LIVING = "LIVING";

    public static int living_count = 0;
    public static int lived_count = 0;

    public static boolean isRuning = false;


    private MyHandler myHandler = new MyHandler();
    private static Listener mListener;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (isRuning == false) {
            isRuning = true;
            MainActivity.isStop = false;
            lived_count = 0;
            living_count = 0;
            next(1, 30000);
            next(3, 2000);
        }

        AccessibilityNodeInfo living_id_1 = findIdView(LIVING_ID_1);
        AccessibilityNodeInfo living_id_2 = findIdView(LIVING_ID_2);
        AccessibilityNodeInfo living_id_3 = findIdView(LIVING_ID_3);

        AccessibilityNodeInfo lived_1 = findTextView(LIVED_1);
        AccessibilityNodeInfo lived_2 = findTextView(LIVED_2);
        AccessibilityNodeInfo lived_3 = findTextView(LIVED_3);

        if (living_id_1 != null || living_id_2 != null || living_id_3 != null) {
            living_count++;
            L.i("living_count:" + living_count);
        }
        if (lived_1 != null || lived_2 != null || lived_3 != null) {
            lived_count++;
            L.i("lived_count:" + lived_count);
        }

        if (living_count > 0 || lived_count > 0) {
            if (!myHandler.hasMessages(2)) {
                myHandler.removeCallbacksAndMessages(null);
                next(2, 5000);
            }
        }

    }

    private class MyHandler extends Handler {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!isRuning) {
                myHandler.removeCallbacksAndMessages(null);
                TShow.showShort("淘宝直播检测已停止");
                return;
            }
            switch (msg.what) {
                case 1:
                    //检查当前界面是否还在所检测的app里
                    if (isThis(MONITOR_PACKAGE_NAMES)) {
                        L.w("返回1");
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        next(1, 2000);
                    } else {
                        L.w("结束1");
                        isRuning = false;
                        result();
                    }
                    break;
                case 2:
                    if (isThis(MONITOR_PACKAGE_NAMES)) {
                        L.w("返回2");
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        next(2, 2000);
                    } else {
                        L.w("结束2");
                        isRuning = false;
                        result();
                    }
                    break;
                case 3:
                    //循环检测当前运行的是否是监测的app
                    if (isThis(MONITOR_PACKAGE_NAMES)) {
                        next(3, 2000);
                    } else {
                        if (myHandler.hasMessages(1)) {
                            result();
                            myHandler.removeCallbacksAndMessages(null);
                            isRuning = false;
                        }
                    }
                    break;
            }
        }
    }

    private void result() {
        if (mListener == null) {
            return;
        }
        if ((living_count == 0 && lived_count == 0) || (living_count > 0 && lived_count > 0)) {
            mListener.fail();
            return;
        }

        if (lived_count > 0) {
            mListener.success(MainActivity.LIVED);
        } else {
            mListener.success(MainActivity.LIVING);
        }
    }

    /**
     * 当启动服务的时候就会被调用
     */
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        L.e("服务已开启");
    }

    /**
     * 中断AccessibilityService的反馈时调用
     */
    @Override
    public void onInterrupt() {
        L.i("中断");
    }

    private void next(final int i, long time) {
        myHandler.sendEmptyMessageDelayed(i, time);

    }

    private void next(final int i) {
        next(i, 2000);
    }

    /**
     * 滑动
     * 滑动比例 0~20
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void slideVertical(final int next, final long nextTime, int startSlideRatio, int stopSlideRatio) {
        int screenHeight = ScreenUtils.getScreenHeight(getApplicationContext());
        int screenWidth = ScreenUtils.getScreenWidth(getApplicationContext());
        L.e("屏幕：" + (screenHeight - (screenHeight / 10)) + "/" +
                (screenHeight - (screenHeight - (screenHeight / 10))) + "/" + screenWidth / 2);

        Path path = new Path();
        int start = (screenHeight / 20) * startSlideRatio;
        int stop = (screenHeight / 20) * stopSlideRatio;
        path.moveTo(screenWidth / 2, start);//如果只是设置moveTo就是点击
        path.lineTo(screenWidth / 2, stop);//如果设置这句就是滑动
        GestureDescription.Builder builder = new GestureDescription.Builder();
        GestureDescription gestureDescription = builder
                .addStroke(new GestureDescription.
                        StrokeDescription(path,
                        200,
                        200))
                .build();

        dispatchGesture(gestureDescription, new AccessibilityService.GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                L.w("滑动结束" + gestureDescription.getStrokeCount());
                next(next, nextTime);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                L.w("滑动取消");
            }
        }, null);
    }

    /**
     * 点击屏幕
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void clickScreen(final int next, final long nextTime, int xRatio, int yRatio) {
        int screenHeight = ScreenUtils.getScreenHeight(getApplicationContext());
        int screenWidth = ScreenUtils.getScreenWidth(getApplicationContext());
        int y = (screenHeight / 20) * yRatio;
        int x = (screenWidth / 20) * xRatio;
        Path path = new Path();
        path.moveTo(x, y);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        GestureDescription gestureDescription = builder
                .addStroke(new GestureDescription.
                        StrokeDescription(path,
                        100,
                        50))
                .build();

        dispatchGesture(gestureDescription, new AccessibilityService.GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                L.w("点击结束" + gestureDescription.getStrokeCount());
                next(next, nextTime);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                L.w("点击取消");
            }
        }, null);
    }

    /**
     * 通过id找控件
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private AccessibilityNodeInfo findIdView(String id, int i) {
        AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
        if (rootInActiveWindow != null) {
            List<AccessibilityNodeInfo> as = rootInActiveWindow.findAccessibilityNodeInfosByViewId(id);
            if (!as.isEmpty()) {
                L.e("findIdView:" + as.size() + "===" + id);
                return as.get(i);
            } else {
                L.e("as:null");
            }
        } else {
            L.e("rootview:null");
        }
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private AccessibilityNodeInfo findIdView(String id) {
        AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
        if (rootInActiveWindow != null) {
            List<AccessibilityNodeInfo> as = rootInActiveWindow.findAccessibilityNodeInfosByViewId(id);
            if (!as.isEmpty()) {
                return as.get(0);
            }
        }
        return null;
    }

    /**
     * 通过文字找控件
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private AccessibilityNodeInfo findTextView(String text, int i) {
        AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
        if (rootInActiveWindow != null) {
            List<AccessibilityNodeInfo> as = rootInActiveWindow.findAccessibilityNodeInfosByText(text);
            if (!as.isEmpty()) {
                return as.get(i);
            }
        }
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private AccessibilityNodeInfo findTextView(String text) {
        AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
        if (rootInActiveWindow != null) {
            List<AccessibilityNodeInfo> as = rootInActiveWindow.findAccessibilityNodeInfosByText(text);
            if (!as.isEmpty()) {
                return as.get(0);
            }
        }
        return null;
    }

    /**
     * 输入内容
     */
    public void paste(AccessibilityNodeInfo a, String text) {
        ClipData clip = ClipData.newPlainText(System.currentTimeMillis() + "", text);
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setPrimaryClip(clip);
        ClipData abc = clipboardManager.getPrimaryClip();
        ClipData.Item item = abc.getItemAt(0);
        L.e("黏贴：" + item.getText().toString());
        a.performAction(AccessibilityNodeInfo.ACTION_PASTE);
    }

    /**
     * 判断当前界面是否是监测的app
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public boolean isThis(String s) {
        AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
        if (rootInActiveWindow != null) {
            return rootInActiveWindow.getPackageName().equals(s) ? true : false;
        }
        return true;
    }


    public static void setListener(Listener listener) {
        mListener = listener;
    }

    public interface Listener {
        void success(String status);

        void fail();
    }
}
